package com.yn.pet.controller.app.biz;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yn.common.core.domain.AjaxResult;
import com.yn.common.core.redis.RedisCache;
import com.yn.common.exception.ServiceException;
import com.yn.pet.controller.pc.response.AppUserInfoResponse;
import com.yn.pet.entity.AppUser;
import com.yn.pet.entity.DeviceGroup;
import com.yn.pet.service.AppUserService;
import com.yn.pet.service.DeviceGroupService;
import com.yn.pet.util.AppTokenUtil;
import com.yn.pet.util.SyncUserUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

@Slf4j
@Service
@AllArgsConstructor
public class AppUserBizService {


    private final WxMaService wxMaService;
    private final AppUserService appUserService;
    private final DeviceGroupService deviceGroupService;

    public AjaxResult getMiniOpenIdByWxCode(String code) {
        Assert.hasText(code, "微信code不能为空");
        Map<String, Object> ajaxResult = new HashMap<>();
        WxMaJscode2SessionResult result;
        try {
            result = wxMaService.jsCode2SessionInfo(code);
        } catch (WxErrorException e) {
            log.error("请求微信，获取小程序openid，unionid 异常：{}", e.getMessage(), e);
            return AjaxResult.error("网路异常，请稍后再试");
        }
        if (result == null) {
            return AjaxResult.error("网路异常，请稍后再试");
        }
        String miniOpenId = result.getOpenid();
        String unionid = result.getUnionid();
        log.info("miniOpenId:{},unionid:{}", miniOpenId, unionid);
        AppUser appUser = appUserService.getMiniOpenid(miniOpenId);
        boolean bn = false;
        if (appUser != null) {
            bn = true;
            String token = AppTokenUtil.createToken(appUser);
            ajaxResult.put("token", token);
        }

        ajaxResult.put("bn", bn);
        return AjaxResult.success(ajaxResult);
    }
//
//    @Transactional
//    public AjaxResult getUserPhoneByCode(String code, String encryptedData, String ivStr) {
//        Assert.hasText(code, "code不能为空");
//        Assert.hasText(encryptedData, "encryptedData不能为空");
//        Assert.hasText(ivStr, "ivStr不能为空");
//        try {
//            WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(code);
//            WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(sessionResult.getSessionKey(), encryptedData, ivStr);
//            String phoneNumber = wxMaPhoneNumberInfo.getPhoneNumber();
//            AppUser appUser = appUserService.getByPhone(phoneNumber);
//            log.info("appUser:{}",appUser);
////            boolean sync = false;
//            if (appUser == null){
//                appUser = new AppUser();
//                appUser.setYnSign(UUID.randomUUID().toString());

    /// /                sync = true;
//            }
//            appUser.setPhone(phoneNumber);
//            appUser.setMiniOpenid(sessionResult.getOpenid());
//            appUser.setWxUnionId(sessionResult.getUnionid());
//            appUser.setCreateTime(new Date());
//            appUser.setUpdateTime(new Date());
//            appUserService.saveOrUpdate(appUser);
//
//            //给用户分组插入一条默认分组信息
//            Long userId = appUser.getAppUserId();
//            DeviceGroup deviceGroup = new DeviceGroup();
//            deviceGroup.setName("默认分组");
//            deviceGroup.setUserId(userId);
//            //创建默认分组
//            LambdaQueryWrapper<DeviceGroup> lambdaQuery1 = Wrappers.lambdaQuery();
//            lambdaQuery1.eq(DeviceGroup::getName, "默认分组")
//                    .eq(DeviceGroup::getUserId, userId);
//            DeviceGroup one = deviceGroupService.getOne(lambdaQuery1);
//            if(one==null){
//                deviceGroupService.save(deviceGroup);
//            }
//
//            String token = AppTokenUtil.createToken(appUser);
//            boolean bn = true;
//            Map<String, Object> map = new HashMap<>();
//            map.put("token", token);
//            map.put("bn", bn);
//            return AjaxResult.success(map);
//        } catch (WxErrorException e) {
//            log.info("获取用户手机号异常：{}", e.getMessage(), e);
//            return AjaxResult.error("网络异常,请稍后再试");
//        }
//
//
//    }
    @Transactional
    public AjaxResult getUserPhoneByCode(String code, String encryptedData, String ivStr) {
        Assert.hasText(code, "code不能为空");
        Assert.hasText(encryptedData, "encryptedData不能为空");
        Assert.hasText(ivStr, "ivStr不能为空");
        try {
            WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(code);
            WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(sessionResult.getSessionKey(), encryptedData, ivStr);
            String phoneNumber = wxMaPhoneNumberInfo.getPhoneNumber();
            AppUser appUser = appUserService.getByPhone(phoneNumber);
            if (appUser == null) {
                appUser = new AppUser();
                appUser.setCreateTime(new Date());
                appUser.setUpdateTime(new Date());
            }
            appUser.setPhone(phoneNumber);
            appUser.setMiniOpenid(sessionResult.getOpenid());
            appUser.setWxUnionId(sessionResult.getUnionid());
            appUserService.saveOrUpdate(appUser);


            //给用户分组插入一条默认分组信息
            Long userId = appUser.getAppUserId();
            DeviceGroup deviceGroup = new DeviceGroup();
            deviceGroup.setName("默认分组");
            deviceGroup.setUserId(userId);
            //创建默认分组
            LambdaQueryWrapper<DeviceGroup> lambdaQuery1 = Wrappers.lambdaQuery();
            lambdaQuery1.eq(DeviceGroup::getName, "默认分组")
                    .eq(DeviceGroup::getUserId, userId);
            DeviceGroup one = deviceGroupService.getOne(lambdaQuery1);
            if (one == null) {
                deviceGroupService.save(deviceGroup);
            }


            String token = AppTokenUtil.createToken(appUser);
            boolean bn = true;
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("bn", bn);
            return AjaxResult.success(map);
        } catch (WxErrorException e) {
            log.info("获取用户手机号异常：{}", e.getMessage(), e);
            return AjaxResult.error("网络异常,请稍后再试");
        }


    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    public AppUserInfoResponse getUserInfo() {
        AppUser appUser = AppTokenUtil.getAppUser();
        if (appUser == null) {
            throw new RuntimeException("当前用户未登录");
        }
        return AppUserInfoResponse.transform(appUser);
    }

//    /**
//     * 同步其他平台用户信息
//     * @param userJson 用户信息
//     * @return 结果
//     */
//    public AjaxResult syncUser(String userJson) {
//        AppUser appUser = JSON.parseObject(userJson,AppUser.class);
//        if (Objects.isNull(appUser)) {
//            throw new ServiceException("用户对象为null");
//        }
//
//        AppUser newUser = new AppUser();
//        newUser.setPhone(appUser.getPhone());
//        newUser.setYnSign(appUser.getYnSign());
//        appUserService.save(newUser);
//        return AjaxResult.success();
//    }
}
